<?php

namespace app\circle\controller;

use app\circle\model\CircleMemberModel;
use app\circle\model\CircleModel;
use app\circle\model\LikeModel;
use app\circle\model\MemberModel;
use app\circle\model\MemberReportModel;
use app\circle\model\ThemeAttentionModel;
use app\circle\model\ThemeModel;
use app\circle\model\ThreplyModel;
use org\util\FileUtil;
use OSS\OssClient;
use think\Request;
use think\Exception;
use think\Log;
use think\Validate;

class ThemeController extends BaseController
{
    private $themeModel;
    private $memberId;
    private $circleModel;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        if ($this->islogin() <= 0) {
            $this->error('请先登陆', url('Public/userLogin', ['reback' => get_current_url()]));
        }
        $this->memberId = $this->getMemberId();
        $this->assign('memberId', $this->memberId);
        $this->themeModel = new ThemeModel();
        $this->circleModel = new CircleModel();
    }

    public function index()
    {
        // 创建SDK实例
        $script = &load_wechat('Script', $this->getWxconfig());
        // 获取JsApi使用签名，通常这里只需要传 $ur l参数
        $options = $script->getJsSign(get_current_url());
        $this->assign('options', $options);
        $type = $this->request->param('type', -1);
        $words = $this->request->param('word', '');
        $circleId = $this->request->param('circle_id', 0);
        $circleIds = $this->request->param('circle_ids/a', []);
        $memberId = $this->request->param('member_id', 0);
        $order = $this->request->param('order', 'create_time desc');
        $circleMemberModel = new CircleMemberModel();
        $circles = $circleMemberModel->where(['member_id'=> $this->memberId,'cm_state'=>1])->field('circle_id,circle_name')->select();
        $this->assign('circles', $circles);
        $attentionModel = new ThemeAttentionModel();
        $shield = $attentionModel->where(['member_id' => $this->memberId, 'type' => 1])->column('attention_theme_id');
        $query = $this->request->param();
        $map = [
            'circle_id' => ['in', array_column($circles->toArray(), 'circle_id')],
            'theme_id' => ['notin', $shield]
        ];
        if (!empty($words)) {
            $map['theme_name'] = ['like', "%$words%"];
        }
        if ($type > -1) {
            $map['theme_type'] = $type;
        }
        if (!empty($circleIds)) {
            $map['circle_id'] = [['in', $circleIds], ['in', array_column($circles->toArray(), 'circle_id')]];
        }
        if (!empty($circleId)) {
            $query['circle_ids'] = [$circleId];
            $map['circle_id'] = [['=', $circleId], ['in', array_column($circles->toArray(), 'circle_id')]];
        }
        if (!empty($memberId)) {
            $map['member_id'] = $memberId;
        }
        $list = $this->themeModel
            ->where($map)
            ->order('is_top desc')
            ->order('is_recommend desc')
            ->order($order)
            ->paginate(10, false, ['query' => $query]);
        foreach ($list as $index => $value) {
            $list[$index]['is_like'] = $value['is_like'];
            $list[$index]['like_list'] = $value['like_list'];
            $list[$index]['reply'] = $value['reply'];
            $list[$index]['theme_image'] = $value['theme_image'];
            $list[$index]['theme_content']['text'] = html_out($value['theme_content']['text']);
            $list[$index]['create_time'] = format_time($str = 'm-d', $value['create_time']);
            $list[$index]['is_attention'] = $attentionModel->where(['member_id' => $this->memberId, 'attention_theme_id' => $value['theme_id'], 'type' => 0])->count();
        }
        if ($this->request->isAjax()) {
            return $list;
        }
        $this->assign('list', $list);
        $this->assign('query', $query);
        return $this->fetch();
    }
    /*圈子分享页面*/
    public function share(){
        return $this->fetch();
    }
    public function info()
    {
        $themeId = $this->request->param('theme_id', 0);
        $themeInfo = $this->themeModel->where('theme_id', $themeId)->find();
        if (empty($themeInfo)) {
            $this->error('帖子未找到或者已被删除');
        }
        $attentionModel = new ThemeAttentionModel();
        $themeInfo['is_attention'] = $attentionModel->where(['member_id' => $this->memberId, 'attention_theme_id' => $themeId, 'type' => 0])->count();
        if ($this->request->isAjax()) {
            return $themeInfo;
        }
        $this->assign('info', $themeInfo);
        return $this->fetch();
    }

    /**
     * 获取会员对应圈子
     */
    public function getMemberCircle()
    {
        $circleId = $this->request->param('circle_id/d', 0);
        $memberCircle = $this->circleModel->getMemberCircle($this->getMemberId());
        foreach ($memberCircle as $key => $value) {
            $memberCircle[$key]['selected'] = '';
            if ($value['circle_id'] == $circleId) {
                $memberCircle[$key]['selected'] = 'selected';
            }
        }
        $data['list'] = $memberCircle;
        return json($data);
    }

    /**
     * 发布主题
     */
    public function publish()
    {
        $data = $this->request->param();
        $result = $this->validate($data, [
            'circle_id|圈子' => 'number|>:0',
            'theme_type|主题类型' => 'number',
            'theme_name|内容' => 'require'
        ]);
        if (true !== $result) {
            $this->error($result);
        }
        $words=cache('sensitive');
        if (PHP_EOL=="\n"){
            $words=str_replace("\r\n",PHP_EOL,$words);
        }else{
            $words=str_replace("\n",PHP_EOL,$words);
        }
        $words=explode(PHP_EOL,$words);
        foreach ($words as $word){
            if (strspn($data['theme_name'],$word)){
                $this->error('您的内容包含关键词'.$word.'，请修改后重试');
            }
        }

        $data['theme_image'] = '';
        if (!empty($data['serverids'])) { //下载微信服务器图片
            $media = &load_wechat('Media', $this->getWxconfig());
            $serverids = explode(',', $data['serverids']);
            Log::record($serverids);
            $themeImage = [];
            foreach ($serverids as $media_id) {
                $result = $media->getMedia($media_id);
                if ($result !== false) {
                    $accessKeyId = config('base.alioss_ak');
                    $accessKeySecret = config('base.alioss_sk');
                    $endpoint = config('base.alioss_endpoint');
                    $bucket = config('base.alioss_bucket');
                    $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, true);
                    $filename = 'upload/image/' . date('Ymd') . '/' . rand_number() . '.jpg';
                    $ossClient->putObject($bucket, $filename, $result);
                    $uploadData['url'] = config('base.upload_prefix') . $filename;
                    $themeImage[] = $uploadData['url'];
                }
            }
            if (!empty($themeImage)) {
                $data['theme_image'] = implode(',', $themeImage);
            }
        }
        $data['member_id'] = $this->getMemberId();
        $this->themeModel->publish($data);
        $this->success('发布成功！');
    }

    /**
     * 设置喜欢或者取消喜欢
     */
    public function setLike()
    {
        $themeId = $this->request->param('theme_id', 0);
        if (empty($themeId)) {
            $this->error('未选择主题');
        }
        $likeModel = new LikeModel();
        $info = $this->themeModel->where('theme_id', $themeId)->value('circle_id');
        $map = ['member_id' => $this->memberId, 'theme_id' => $themeId];
        $count = $likeModel->where($map)->count();
        if ($count) {
            if ($likeModel->where($map)->delete()) {
                $this->themeModel->where('theme_id', $themeId)->setDec('theme_likecount');
                $likeModel = new LikeModel();
                $likelist = $likeModel->where('theme_id', $themeId)->select();
                foreach ($likelist as $index => $item) {
                    $likelist[$index]['member_name'] = $item['member_name'];
                }
                $this->success('取消点赞成功', '', $likelist);
            } else {
                $this->error('取消点赞失败');
            }
        } else {
            $data = [
                'theme_id' => $themeId,
                'member_id' => $this->memberId,
                'circle_id' => $info
            ];
            if ($likeModel->addData($data)) {
                $this->themeModel->where('theme_id', $themeId)->setInc('theme_likecount');
                $likeModel = new LikeModel();
                $likelist = $likeModel->where('theme_id', $themeId)->select();
                foreach ($likelist as $index => $item) {
                    $likelist[$index]['member_name'] = $item['member_name'];
                }
                $this->success('点赞成功', '', $likelist);
            } else {
                $this->error('点赞失败');
            }
        }
    }

    /**
     * 获取评论
     * @return array|mixed|\think\Paginator
     */
    public function getThreply()
    {
        $themeId = $this->request->param('theme_id', 0);
        if (empty($themeId)) {
            return ['last_page' => 0];
        }
        $limit = $this->request->param('limit', 10);
        $model = new ThreplyModel();
        $list = $model
            ->where(['theme_id' => $themeId, 'is_closed' => 0, 'reply_replyid' => 0])
            ->paginate($limit);
        foreach ($list as $index => $item) {
            $list[$index]['reply'] = $item['reply'];
        }
        if ($this->request->isAjax()) {
            return $list;
        }
        $this->assign('list', $list);
        return $this->fetch();
    }

    /**
     * 发表评论
     */
    public function replay()
    {
        if ($this->request->isAjax()) {
            $data = $this->request->param();
            $validate = new Validate([
                ['theme_id', 'require', '请选择回复的主题'],
                ['reply_content', 'require', '请填写回复内容']
            ]);
            $result = $validate->check($data);
            if (!$result) {
                $this->error($validate->getError());
            }
            $themeInfo = $this->themeModel->where('theme_id', $data['theme_id'])->find();
            $memberModel = new MemberModel();
            $replyModel = new ThreplyModel();
            $memberInfo = $memberModel->where('member_id', $this->memberId)->find();
            $replyReplyid = 0;
            $replyReplyname = '';
            if (!empty($data['reply_replyid'])) {
                $replyReplyid = $data['reply_replyid'];
                $replyReplyname = $replyModel->where('reply_id', $replyReplyid)->value('member_name');
            }
            $data += [
                'circle_id' => $themeInfo['circle_id'],
                'member_id' => $this->memberId,
                'member_name' => $memberInfo['member_truename'],
                'reply_replyid' => $replyReplyid,
                'reply_replyname' => $replyReplyname,
                'is_closed' => 0
            ];
            if ($replyModel->addData($data)) {
                $this->themeModel->where('theme_id', $data['theme_id'])->setInc('theme_commentcount');
                $this->success('评论成功', '', $data);
            } else {
                $this->error('评论失败');
            }

        }
        return $this->fetch();
    }

    public function attention()
    {
        $themeId = $this->request->param('theme_id', 0);
        $type = $this->request->param('type', 0);
        $typeText = [0 => '收藏', 1 => '屏蔽'];
        if (empty($themeId)) {
            $this->error('帖子指定错误');
        }
        $data = [
            'attention_theme_id' => $themeId,
            'type' => $type,
            'member_id' => $this->memberId
        ];
        $model = new ThemeAttentionModel();
        if ($model->where($data)->delete()) {
            $this->success('取消' . $typeText[$type] . '成功');
        } else {
            if ($model->addData($data)) {
                $this->success($typeText[$type] . '成功');
            } else {
                $this->error($typeText[$type] . '失败');
            }
        }
    }

    public function del()
    {
        $themeId = $this->request->param('theme_id', 0);
        if ($this->themeModel->where(['theme_id' => $themeId, 'member_id' => $this->memberId])->delete()) {
            $map=['theme_id'=> $themeId];
            $model = new ThreplyModel();
            $model->where($map)->delete();
            $model=new LikeModel();
            $model->where($map)->delete();
            $model=new ThemeAttentionModel();
            $model->where('attention_theme_id',$themeId)->delete();

            $this->success('删除成功');
        } else {
            $this->error($this->themeModel->getError());
        }
    }

    public function report()
    {
        $data = $this->request->param();
        $validate = new Validate([
            ['theme_id', 'require', '请选择举报内容'],
            ['msg', 'require', '请填写举报理由']
        ]);
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        $themeInfo = $this->themeModel->where(['theme_id'=> $data['theme_id']])->find();
        if (empty($themeInfo)) {
            $this->error('未找到相应内容');
        }
        $data = ['theme_id' => $themeInfo['theme_id'],
            'report_member_id' => $themeInfo['member_id'],
            'member_id'=>$this->memberId,
            'msg'=>$data['msg']
        ];
        $model=new MemberReportModel();
        if ($model->addData($data)){
            $this->success('举报成功,你可以在个人中心查看处理结果');
        }else{
            $this->error('举报失败,请稍后再试');
        }
    }



}